package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.github.pagehelper.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public Result addNewDish(DishDTO dishDTO) {

        Dish dish = Dish.builder()
                .name(dishDTO.getName())
                .categoryId(dishDTO.getCategoryId())
                .price(dishDTO.getPrice())
                .image(dishDTO.getImage())
                .description(dishDTO.getDescription())
                .status(dishDTO.getStatus())
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .createUser(BaseContext.getCurrentId())
                .updateUser(BaseContext.getCurrentId())
                .build();
        // 执行插入操作
        dishMapper.insert(dish);
        //获取菜品id
        Long insertedId = dish.getId();
        System.out.println( "主键id为;"+insertedId);
       //如果主键不为空 那么添加菜品成功 添加菜品口味
        if(insertedId!=null){
            List<DishFlavor> flavors = dishDTO.getFlavors();
            for (DishFlavor originalFlavor : flavors) {
                DishFlavor dishFlavor = DishFlavor.builder()
                        .dishId(insertedId  )
                        .name(originalFlavor.getName())
                        .value(originalFlavor.getValue())
                        .build();
                // 保存操作
                dishFlavorMapper.insert(dishFlavor);
            }
        }else {
            String message = "新增菜品失败";
            return Result.error(message);

        }
        String message = "新增菜品成功";
        return Result.success(message);

    }

     /**
     * 菜品查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //开启分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Dish dish = new Dish();
        dish.setName(dishPageQueryDTO.getName());
        dish.setStatus(dishPageQueryDTO.getStatus());
        //如果分类id不为空
        if(dishPageQueryDTO.getCategoryId() != null){
            dish.setCategoryId(Long.valueOf(dishPageQueryDTO.getCategoryId()));
        }

        Page<Dish> page = dishMapper.pageQuery(dish);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int delete(List<Long> ids) {

        int i = dishMapper.deleteByDishIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
        return i;
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */

    @Override
    @Transactional
    public Result update(DishDTO dishDTO) {
        //先修改菜品表
       Dish dish = Dish.builder()
                .id(dishDTO.getId())
                .name(dishDTO.getName())
                .categoryId(dishDTO.getCategoryId())
                .price(dishDTO.getPrice())
                .image(dishDTO.getImage())
                .description(dishDTO.getDescription())
                .status(dishDTO.getStatus())
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        int update = dishMapper.update(dish);
        if(update>0){
            //删除菜品口味表中的数据

                dishFlavorMapper.deleteById(dishDTO.getId());


            //添加新的菜品口味数据
            List<DishFlavor> flavors = dishDTO.getFlavors();
            for (DishFlavor originalFlavor : flavors) {
                DishFlavor dishFlavor = DishFlavor.builder()
                        .dishId(dishDTO.getId())
                        .name(originalFlavor.getName())
                        .value(originalFlavor.getValue())
                        .build();
                        dishFlavorMapper.insert(dishFlavor);
            }
        }
        String message = "修改菜品成功";
        return  Result.success(message);
    }

    /**
     * 根据id查询菜品和对应的口味
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        DishVO dishvo = dishMapper.getByIdWithFlavor(id);

        return dishvo;
    }

    @Override
    public Result startOrStop(Integer status, Long id) {

        if (dishMapper.startOrStop(status, id)>0){
            return Result.success(MessageConstant.ADD_SUCCESS);
        }else {
            return Result.error("订单删除失败");
        }

    }

    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
      return dishMapper.selectByCategoryId(categoryId);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
